import datetime
import uuid

from django.http import JsonResponse
from django.shortcuts import render, redirect

from web import models
from utils.pagination import Pagination  # 导入分页计算函数


def organindex(request):
    # 判断会员到期没有，到期了，不能访问
    user_mobile_phone = request.session.get('user_mobile_phone', 0)  # 没有就user_id为0
    # 获取session中的user_id,如果用户登陆了，坑等有，如果没有登陆，就没有
    user_object = models.organization.objects.filter(mobile_phone=user_mobile_phone).first()
    if user_object:  # 木有登陆正确的账号
        v = models.trade.objects.filter(org_id=user_object.org_id).filter(status="2").order_by(
            "-crdate").first()
        if v:  # 有没有单子
            if v.end >= datetime.datetime.now():  # 没有到期
                guser_object = models.guser.objects.filter(org_id=user_object.org_id).order_by('job_id')  # 从小到大
                if guser_object:  # 如果有的话

                    page_object = Pagination(
                        current_page=request.GET.get("page"),  # 当前访问的分页
                        all_count=guser_object.count(),  # 统计有多少条数据
                        base_url=request.path_info,
                        query_params=request.GET,
                        per_page=10,  # 每页显示的数据
                        pager_page_count=11  # 展示的总页数

                    )

                    guser_list = guser_object[page_object.start:page_object.end]

                    return render(request, 'web/organindex.html',
                                  {"guser_list": guser_list, "page_html": page_object.page_html()})
                else:
                    guser_list = "没有人员"
                    return render(request, 'web/organindex.html', {"guser_list": guser_list})
            else:
                return redirect('/web/price/')
        else:

            return redirect('/web/price/')
    else:
        return redirect('/web/login/')


def organinvite(request):
    # 判断会员到期没有，到期了，不能访问
    user_mobile_phone = request.session.get('user_mobile_phone', 0)  # 没有就user_id为0
    # 获取session中的user_id,如果用户登陆了，坑等有，如果没有登陆，就没有
    user_object = models.organization.objects.filter(mobile_phone=user_mobile_phone).first()
    if user_object:  # 木有登陆正确的账号
        v = models.invite.objects.filter(org_id=user_object.org_id).first()
        if request.method == 'GET':
            if v:  # 没有邀请码 ，则没有购买，不管过没过期，都可以访问，邀请码页面
                return render(request, 'web/organinvite.html', {"v": v})

            else:
                return redirect('/web/price/')
        else:
            if v:
                check1 = request.POST.get("check1")
                check2 = request.POST.get("check2")
                if check1 == "option1":
                    uid = str(uuid.uuid4())
                    invitestr = uid[0:8]
                    v.invite = invitestr
                if check2 == "option2":
                    v.status = 1
                else:
                    v.status = 2

                try:
                    v.save()
                except Exception:
                    return JsonResponse({"status": False})
                else:
                    return JsonResponse({"status": True})
    else:
        return redirect('/web/login/')


# 问题编辑
def organclock(request):
    user_mobile_phone = request.session.get('user_mobile_phone', 0)  # 没有就user_id为0
    # 获取session中的user_id,如果用户登陆了，坑等有，如果没有登陆，就没有
    user_object = models.organization.objects.filter(mobile_phone=user_mobile_phone).first()
    if user_object:  # 木有登陆正确的账号
        v = models.trade.objects.filter(org_id=user_object.org_id).filter(status="2").order_by(
            "-crdate").first()
        if v:  # 有没有单子
            if v.end >= datetime.datetime.now():  # 没有到期

                      question_object = models.question.objects.filter(org_id=user_object.org_id).first()  # 查问题表，看有没有创建问题表

                      if request.method=="GET":
                                if question_object:  # 如果有的话返回问题导图页面上

                                    qulist = []
                                    list2 = []
                                    if question_object.question1:
                                        qulist.append(question_object.question1)
                                    if question_object.question2:
                                        qulist.append(question_object.question2)
                                    if question_object.question3:
                                        qulist.append(question_object.question3)
                                    if question_object.question4:
                                        qulist.append(question_object.question4)
                                    if question_object.question5:
                                        qulist.append(question_object.question5)
                                    if question_object.question6:
                                        qulist.append(question_object.question6)
                                    if question_object.question7:
                                        qulist.append(question_object.question7)
                                    if question_object.question8:
                                        qulist.append(question_object.question8)
                                    if question_object.question9:
                                        qulist.append(question_object.question9)
                                    if question_object.question10:
                                        qulist.append(question_object.question10)
                                    if question_object.question11:
                                        qulist.append(question_object.question11)

                                    for i in range(1, 13):
                                        list2.append(i)

                                    dic_new = dict(zip(list2, qulist))
                                    print(dic_new)

                                    return render(request, 'web/organclock.html',
                                                  {"qulist": dic_new})
                                else:
                                    qulist = False
                                    return render(request, 'web/organclock.html', {"qulist": qulist})
                      else:
                                  if  question_object : #有获取参数
                                      if request.POST.get("1"):
                                          question_object.question1=request.POST.get("1")
                                      else:
                                          question_object.question1 = ""
                                      if request.POST.get("2"):
                                          question_object.question2=request.POST.get("2")
                                      else:
                                          question_object.question2 = ""
                                      if request.POST.get("3"):
                                          question_object.question3 = request.POST.get("3")
                                      else:
                                          question_object.question3 = ""

                                      if request.POST.get("4"):
                                          question_object.question4 = request.POST.get("4")
                                      else:
                                          question_object.question4 = ""
                                      if request.POST.get("5"):
                                          question_object.question5=request.POST.get("5")
                                      else:
                                          question_object.question5 = ""
                                      if request.POST.get("6"):
                                          question_object.question6=request.POST.get("6")
                                      else:
                                          question_object.question6 = ""
                                      if request.POST.get("7"):
                                          question_object.question7 = request.POST.get("7")
                                      else:
                                          question_object.question7 = ""
                                      if request.POST.get("8"):
                                          question_object.question8 = request.POST.get("8")
                                      else:
                                          question_object.question8 = ""
                                      if request.POST.get("9"):
                                          question_object.question9 = request.POST.get("9")
                                      else:
                                          question_object.question9 = ""
                                      if request.POST.get("10"):
                                          question_object.question10 = request.POST.get("10")
                                      else:
                                          question_object.question10 = ""
                                      if request.POST.get("11"):
                                          question_object.question11 = request.POST.get("11")
                                      else:
                                          question_object.question11 = ""

                                      question_object.save()
                                      return JsonResponse({"status": True})

                                  else: #创建一个
                                      models.question.objects.create(  # 订单写入数据库
                                          org_id=user_object.org_id,
                                          question1="您自己是否疑似患新型肺炎（隔离中等待医院检验结果）",
                                          question2="您自己是否确诊患新型肺炎（医院已出具确诊证明）",
                                          question3="您家人是否疑似患新型肺炎",
                                          question4="您家人是否确诊患新型肺炎",
                                          question5="您是否发热（体温大于37.3）",
                                          question6="您是否有呼吸道感染症状（咳嗽、气促等症状）",
                                          question7="您是否今日在家",
                                          question8="您是否接触过疑似或确诊病例",
                                      )
                                      return JsonResponse({"status": True})
            else:
             return redirect('/web/price/')
        else:
             return redirect('/web/price/')
    else:
        return redirect('/web/login/')


def organstaff(request):  # 人员管理
    # 判断会员到期没有，到期了，不能访问
    user_mobile_phone = request.session.get('user_mobile_phone', 0)  # 没有就user_id为0
    # 获取session中的user_id,如果用户登陆了，坑等有，如果没有登陆，就没有
    user_object = models.organization.objects.filter(mobile_phone=user_mobile_phone).first()
    if user_object:  # 木有登陆正确的账号
        v = models.trade.objects.filter(org_id=user_object.org_id).filter(status="2").order_by(
            "-crdate").first()
        if v:  # 有没有单子
            if v.end >= datetime.datetime.now():  # 没有到期
                guser_object = models.guser.objects.filter(org_id=user_object.org_id).order_by('job_id')  # 从小到大

                if guser_object:  # 如果有的话
                    if request.method == "GET":
                        page_object = Pagination(
                            current_page=request.GET.get("page"),  # 当前访问的分页
                            all_count=guser_object.count(),  # 统计有多少条数据
                            base_url=request.path_info,
                            query_params=request.GET,
                            per_page=10,  # 每页显示的数据
                            pager_page_count=11  # 展示的总页数

                        )

                        guser_list = guser_object[page_object.start:page_object.end]

                        return render(request, 'web/organstaff.html',
                                      {"guser_list": guser_list, "page_html": page_object.page_html()})
                    else:

                        id = request.POST.get("ID")
                        moible = request.POST.get("mobile")
                        user = models.guser.objects.filter(job_id=id).filter(mobile_phone=int(moible)).first()
                        try:
                            user.delete()
                        except Exception:
                            return JsonResponse({"status": False})

                        else:
                            return JsonResponse({"status": True})

                else:
                    guser_list = "没有人员"
                    return render(request, 'web/organstaff.html', {"guser_list": guser_list})
            else:
                return redirect('/web/price/')
        else:

            return redirect('/web/price/')
    else:
        return redirect('/web/login/')
